from PySide2.QtCore import Qt, Signal, Slot
from PySide2.QtWidgets import QDialog, QVBoxLayout, QLabel, QProgressBar, QMessageBox

global win
global App


class ProgressDialog(QDialog):
    progress_signal = Signal(int)
    complete_signal = Signal(str, str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("正在下载更新...")
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint & ~Qt.WindowCloseButtonHint)

        self.layout = QVBoxLayout()

        self.label = QLabel("请勿关闭客户端，下载完成后程序将自动重启")
        self.layout.addWidget(self.label)

        self.progress_bar = QProgressBar(self)
        self.layout.addWidget(self.progress_bar)

        self.setLayout(self.layout)

        self.progress_signal.connect(self.update_progress)
        self.complete_signal.connect(self.handle_complete)

    @Slot(int)
    def update_progress(self, value):
        self.progress_bar.setValue(value)

    @Slot(str, str)
    def handle_complete(self, temp_file, error):
        from UserCareSystem_OnlyC import replace_and_restart
        if error:
            QMessageBox.critical(self, "下载失败", error)
        elif temp_file:
            self.close()
            replace_and_restart(temp_file, win, App)
